package com.sq.partner.manager.controller;

import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.sq.partner.manager.common.Constants;
import com.sq.partner.manager.mybatis.model.GatewayUser;
import com.sq.partner.manager.mybatis.model.NocarProd;
import com.sq.partner.manager.service.RuleInfoService;
import com.sq.partner.manager.util.*;

@Controller
@RequestMapping("/prodManage")
public class ProdManageController {
	private static Logger logger = LogUtil.getLog(ProdManageController.class);
	
	@Resource
	RuleInfoService ruleInfoService;
	
	
	@RequestMapping(value = "/edit")
	public String edit(ModelMap model,HttpServletRequest request) throws Exception {
		
		return "facadeManage/prodManage/edit";
	}
	
	
	@RequestMapping(value = "/queryPlans")
	@ResponseBody
	public List<Map<String,String>> queryPlanInfoPageByCriteria(ModelMap model,HttpServletRequest request , HttpSession session ) throws SQLException{
		GatewayUser user=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		String deptCode = user.getDepartmentStr();
		String userCodes=com.sq.partner.manager.common.Config.getProp("imple.nlife.userCodes");
		logger.info("登录用户名："+user.getUserCode()+"   配置的用户名： "+userCodes);		
		List<Map<String,String>> plans = ruleInfoService.queryNlifePlans(deptCode);		
		return plans;
	}
	
	
	@RequestMapping(value = "/saveOrUpdateInfo")
	@ResponseBody
	public void saveOrUpdateQcCodeInfo(String planNo,String planDesc,String planSpecial1,String planSpecial2,String planSpecial3,String planIntro,String planNotice) throws Exception{
		//删除原有数据，添加新数据
		ruleInfoService.deletOldInfoByPlanNo(planNo);
		//分类增加新数据
		Map<String,String> map = new HashMap<String, String>();
		map.put("planNo", planNo);
		map.put("planDesc", planDesc);
		map.put("planSpecial1",planSpecial1);
		map.put("planSpecial2",planSpecial2);
		map.put("planSpecial3",planSpecial3);
		map.put("planIntro",planIntro);
		map.put("planNotice",planNotice);
		//新增数据
		ruleInfoService.insertNewPlanInfo(map);
		
	}
	
	@RequestMapping(value = "/queryPlanInfosByPlanNo")
	@ResponseBody
	public Map<String,String> queryPlanInfosByPlanNo(String planNo) throws Exception{
		Map<String,String> rsmap = new HashMap<String,String>();
		
		rsmap = ruleInfoService.queryPlanInfosByPlanNo(planNo);
		return rsmap;
	}
	
	@RequestMapping(value = "/riskFileImport")
	public String toRiskFileImport(ModelMap model,HttpServletRequest request) throws Exception{
		return "facadeManage/riskFileImport/riskFileImport";
	}
	
	/**
	 * word上传
	 */
	@RequestMapping(value = "/riskFileUpload")
	public void riskFileUpload(@RequestParam MultipartFile[] myfiles,HttpServletResponse response, HttpSession session) throws Exception {
		//设置编码格式
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		
		PrintWriter out = null;
		List<InputStream> inputStreams = null;
		Page<String>  page = new Page<String>();
		try {
			//获取writer对象。
			out = response.getWriter();
			if (myfiles.length < 1) {
				//当myfiles长度小于1，上传为空，返回报错信息
				page.setResult("error");
				page.setMessage("请添加上传文件!");
			}else{
				//获取当前操作人员信息；
				GatewayUser user = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
				inputStreams=ruleInfoService.getFileInputStream(myfiles);	
				logger.info("读写成功");
				page.setResult("success");
				page.setMessage((String)session.getAttribute("result"));
			}
		} catch (Exception e) {
			logger.info("---------读取条款文件失败---------",e);
			page.setResult("error");
			page.setMessage(e.getMessage());
		} finally {
			if(null!=inputStreams){
				for (InputStream input:inputStreams){
					try{
						input.close();
					}catch(Exception e){
						logger.warn("关闭流失败！", e);
					}
				}
			}
			out.write(JsonUtils.toJson(page));
			try {
				out.close();
			} catch (Exception e) {
				logger.warn("关闭流失败！", e);
			}
		}
	}
	
	@RequestMapping(value = "/loadRiskContent")
	@ResponseBody
	public Page<Map<String,String>> loadRiskContent(ModelMap model,HttpServletRequest request , HttpSession session ,String riskCode,
			String riskName,int current , int size) throws Exception{
		
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("riskCode", "%" + riskCode + "%");
		map.put("riskName", "%" + riskName + "%");
		map.put("startCount", (current - 1) * size);
		map.put("endCount", current * size);
		List<Map<String,String>> list = new ArrayList<Map<String,String>>();
		list = ruleInfoService.loadRiskContent(map);
		List<Map<String,String>> rsList = new ArrayList<Map<String,String>>();
		for(Map<String,String> param : list){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String date = sdf.format(param.get("LAST_OPERATE_TIME"));
			param.put("LAST_OPERATE_TIME", date);
			rsList.add(param);
		}
	
		Page<Map<String,String>> page = new Page<Map<String,String>>();
			page.setData(rsList);
			page.setCurrent(current);
			int count = ruleInfoService.loadRiskContentCount(map);
			int maxPage = (int) Math.ceil(((double)count/size));
			page.setMaxPage(maxPage);
		return page;
	}
	//导入前查一下是否已存在
	@RequestMapping(value = "/isRiskFileExist")
	@ResponseBody
	public Page<Map<String,String>> isRiskFileExist(String riskCode,ModelMap model,HttpServletRequest request , HttpSession session ) throws Exception{
		boolean rs = ruleInfoService.isRiskFileExist(riskCode);
		Page<Map<String,String>> page = new Page<Map<String,String>>();
		if(rs){
			page.setResult("warning");
		}else{
			page.setResult("success");
		}
		return page;
	}
	
	
	//预览条款文件
	@RequestMapping(value = "/previewRiskContent")
	@ResponseBody
	public Page<Map<String,String>> previewRiskContent(String riskCode,ModelMap model,HttpServletRequest request , HttpSession session ) throws Exception{
		Page<Map<String,String>> page = new Page<Map<String,String>>();
		
		String message = ruleInfoService.previewRiskContent(riskCode);
		
		page.setMessage(message);
		return page;
	}
	
	/**
	 * 查询方案列表
	 * @param size
	 * @param current
	 * @param tradProdCode
	 * @throws Exception 
	 */
	@RequestMapping(value = "/queryPlanList")
	public @ResponseBody Page<Map<String,Object>> queryPlanList(Integer size,Integer current,String planCode,String planName,HttpSession session) throws Exception{
		Map<String,Object> map=new HashMap<String, Object>();
		Page<Map<String,Object>> page=new Page<Map<String,Object>>();
		page.setCurrent(current);
		page.setSize(size);
		if(current != null && current != -1){
			page.setCurrent(current);
			map = SqlUtil.buildPageMap(page);
		}
		GatewayUser user=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		String deptCode = user.getDepartmentStr();
		String userCodes=com.sq.partner.manager.common.Config.getProp("imple.nlife.userCodes");
		logger.info("登录用户名："+user.getUserCode()+"   配置的用户名： "+userCodes);	
		map.put("value", deptCode==null?"''":deptCode.substring(1, 3));
		map.put("planCode", planCode);
		map.put("planName", planName);
		page.setType(map);
		return ruleInfoService.queryPlanPageByCriteria(page);
	}
	
}
